
import validator from '../util/validator'
import constant from '../util/constant'
const utilService = {
    // 浏览器queryparams ==> object
    getUrlParams: function () {
        //去除?符号
        var url = window.location.search;
        var params = url.length > 0 ? url.substr(1) : "";
        var args = {};
        var pArr = params.length ? params.split('&') : [];
        for (var i = 0; i < pArr.length; i++) {
            var item = pArr[i].split("=");
            var name = decodeURIComponent(item[0]);
            var value = decodeURIComponent(item[1]);
            if (name.length > 0) {
                args[name] = value;
            }
        }
        return args;
    },
    /**
     * 滚动显示
     * @param {*} dom 滚动dom上挂的节点 
     * @param {*} time 滚动速度(间隔时间)
     * @param {*} time2 停顿时间
     * @param {*} waitDistance 滚动停顿
     * @param {*} moveDistance 移动距离 
     * @param {*} startScroll 是否滚动 
     */
    scrollView: function (options) {
        options.time = options.time || 0;
        options.time2 = options.time2 || 1000;
        options.waitDistance = options.waitDistance || 17;
        options.moveDistance = options.moveDistance || 0;
        options.startScroll = options.startScroll || false;
        const self = this;
        var scrollTime = window.setTimeout(function () {
            options.moveDistance++;
            var scrollTotal = options.dom[0].scrollHeight;
            // console.log('total:' + scrollTotal + ',move:' + options.moveDistance);
            // 首行不滚动
            if (!options.startScroll && options.moveDistance < options.waitDistance) {
                self.scrollView(options);
                // 每行结束
            } else if (/^\d+$/.test(options.moveDistance / options.waitDistance)) {
                window.setTimeout(function () {
                    // 首行开始滚动
                    if (!options.startScroll && options.moveDistance / options.waitDistance == 1) {
                        options.moveDistance = 0;
                        options.startScroll = true;
                        // 最后行开始，重置滚动
                    } else if (options.moveDistance + 1 >= scrollTotal - options.waitDistance) {
                        options.moveDistance = 0;
                        options.startScroll = false;
                        options.dom.scrollTop(options.moveDistance);
                        // options.dom.animate({
                        //   scrollTop: options.moveDistance
                        // }, 500);
                    }
                    self.scrollView(options);
                }, options.time2);
            } else {
                options.dom.scrollTop(options.moveDistance);
                self.scrollView(options);
            }
        }, options.time);
    },
    /**
     * 表单验证
     * ruleArr 参数列表
     * obj 提交参数
     */
    validate: function (ruleArr, obj) {
        for (var i = 0; i < ruleArr.length; i++) {
            var key = ruleArr[i];
            var value = obj[key];
            if (value && value !== '') {
                if (validator[key] && !validator[key].test(value)) {
                    return {
                        status: false,
                        msg: constant.ERROR[key],
                        name: key
                    };
                }
            } else {
                const errorMsg = constant.ERROR[key];
                return {
                    status: false,
                    msg: !errorMsg ? constant.ERROR['emptyDefault'] : errorMsg,
                    name: key
                };
            }
        }
        return {
            status: true
        };
    },
    setError: function($dom, result) {
        var self = this;
        self.clearError($dom);
        $dom.find('input, textarea').bind('focus', function (event) {
            self.clearError($dom);
        })
        let type = self.queryType($dom, result.name) || 'input';
        $dom.find(type + '[name="' + result.name + '"]').nextAll('.JS-error-msg').show().text(result.msg || result.resultMsg || constant.ERROR['emptyDefault'])
    },
    // setError: function ($dom, result) {
    //     var self = this;
    //     self.clearError($dom);
    //     $dom.find('.JS-errorWrap').show().find('.JS-errorMsg').text(result.msg || result.resultMsg || constant.ERROR['emptyDefault']);
    //     $dom.find('input, textarea').bind('focus', function (event) {
    //         self.clearError($dom);
    //     }).blur(function () {
    //         $(this).parent().removeClass('focus');
    //     });
    //     let type = self.queryType($dom, result.name) || 'input';
    //     $dom.find(type + '[name="' + result.name + '"]').parent('li').addClass('focus-err');
    // },
    queryType: function ($dom, name) {
        let types = ['input', 'select', 'textarea'];
        let result = '';
        types.map(item => {
            if ($dom.find(item + '[name="' + name + '"]').length > 0) {
                result = item;
                return;
            }
        })
        return result;
    },
    // 清除错误信息
    clearError: function ($dom) {
        // $dom.find('.focus-err').removeClass('focus-err');
        $dom.find('.JS-error-msg').hide().text('');
    },
    /**
     * 表单数据获取
     * 获取$dom下子元素（标签input textarea selecte） 属性为name="name"的value
     * $dom 表单dom
     * name 表单元素属性name='telephone'
     */
    getValue: function ($dom, name) {
        if ($dom.find('input[name="' + name + '"]').length > 0) {
            return $dom.find('input[name="' + name + '"]').val();
        } else if ($dom.find('textarea[name="' + name + '"]').length > 0) {
            return $dom.find('textarea[name="' + name + '"]').val();
        } else if ($dom.find('select[name="' + name + '"]').length > 0) {
            return $dom.find('select[name="' + name + '"]').val();
        } else {
            return '';
        }
    },
    // url跳转
    toHref: function (url) {
        let backUrl = this.getUrlParams()['backUrl'];
        if (backUrl) {
            window.location.href = backUrl;
        } else {
            window.location.href = url ? url : '/';
        }
    },
    toLoginUrl: function (backUrl) {
        let loginUrl = '/user/login';
        if (!backUrl) {
            window.location.href = loginUrl;
        } else {
            window.location.href = loginUrl + '?backUrl=' + window.encodeURIComponent(backUrl);
        }
    },
    isLogin: function () {
        var uid = $.cookie('uid');
        var token = $.cookie('token');
        if (uid && uid.length > 1 && token && token.length) {
            return true;
        } else {
            return false;
        }
    },
    showContent: function (options = {}) {
        options.contentDom = options.contentDom || 'JS-content';
        options.$contentDom = $('.' + options.contentDom);
        options.index = options.index || 0;
        options.$contentDom.hide();
        $('.' + options.contentDom + '[data-content="' + options.index + '"]').show();
    },
    showModel: function (val) {
        let dom = val || 'JS-content';
        $('.' + dom).show();
    },
    hideModel: function (val) {
        let dom = val || 'JS-content';
        $('.' + dom).hide();
    },
    // 倒计时
    countDown: function ($dom, time = constant.CountDown) {
        const self = this;
        self.disableDom($dom, true);
        if (!time) {
            time = constant.CountDown;
            self.disableDom($dom, false);
            $dom.text(constant.SmsBtnText);
            return;
        }
        time--;
        setTimeout(function () {
            $dom.text(`${time}秒后重新获取`);
            self.countDown($dom, time);
        }, 1000);
    },
    // dom失效
    disableDom: function ($dom, type) {
        if ($dom) {
            type = type ? type : false;
            $dom.attr({
                disabled: type
            });
        }
    },
    // [strToArr 字符串转数组 1,2,3,4->[1,2,3,4,5]]
    strToArr: function (str, format) {
        if (str) {
            return str.split(format || ',');
        } else {
            return [];
        }
    },
    getAttrValue: function ($dom, key) {
        return $dom.attr(key);
    },
    getRestfulParam: function () {
        let pathname = window.location.pathname;
        let paramsArr = pathname ? pathname.split('/') : [];
        return paramsArr[paramsArr.length - 1];
    },
    /**
     * 设置value
     * $dom jq对象：根据jq dom查询
     * $dom string 根据属性名查询
     */
    setValue: function ($dom, value) {
        try {
            if ($dom && $dom.length > 0 && $dom.context) {
                $dom.val(value);
            } else if ($dom && typeof $dom == 'string') {
                $('[' + $dom + ']').val(value);
            }
        } catch (err) {

        }
    },
    /**
     * 设置文本
     * $dom jq对象：根据jq dom查询
     * $dom string 根据属性名查询
     */
    setText: function ($dom, value) {
        try {
            if ($dom && $dom.length > 0 && $dom.context) {
                $dom.text(value);
            } else if ($dom && typeof $dom == 'string') {
                $('[' + $dom + ']').text(value);
            }
        } catch (err) {

        }
    },
    readSecond: function (time, text, href) {
        var minute = time;
        var text = text;
        var second = setInterval(function () {
            if (minute === 0) {
                clearInterval(second);
                window.location.href = href
            } else {
                minute--;
                utilService.showTipDialog(minute + text, 'none', '', 'open');
            }
        }, 1000)
    },
    getArray: function (str, format) {
        return str ? str.split(format || ',') : [];
    },
    bindEvent: function ($dom, cb, event) {
        $dom.on(event || 'click', cb);
    },
    splitBySpace: function (cardNo) {
        var len = cardNo.length,
            oldLen = cardNo.length,
            start = 1,
            newVal = '';
        while (len >= 0) {
            newVal += cardNo.substr(start - 1, 4);
            if (len > 4) {
                newVal += ' ';
            }
            len -= 4;
            start += 4;
        }
        return newVal;
    },
    saveCookie: function (key, value, options) {
        if (value) {
            $.cookie(key, value);
        }
    },
    getUserAgent() {
        let userAgent = navigator.userAgent.indexOf("iPhone") != -1 ? "IOS" : "ANDROID";
		return userAgent;
    },
    // 挂在二维码
    buildQrcodeImg: function ($dom, url) {
        // console.log(url);
        $dom.attr({
            src: url
        });
    },
    // 生成二维码链接
    buildQrcodeUrl: function (url, encode) {
        if (encode) {
            url = encodeURIComponent(url);
        }
        return '/napi/share/qrcode?url=' + url;
    },
    // 构建微信授权链接
    buildWxOAuthUrl: function (redirectUrl, encode) {
        let appId = WX_APPID;
        let redirect_uri = encode ? encodeURIComponent(redirectUrl) : redirectUrl;
        return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
    },
    // 构建微信重定向链接
    buildWxRedirectUrl: function (url) {
        return WX_CALLBACK_URL + `/wx/redirectOAuthInfo?backUrl=${url}`;
    },
    dealSpaUrl: function (url) {
        if (url && url.indexOf('#')) {
            return url.replace('#', '@');
        }
        return url;
    }
}
export default utilService;